package com.yyfax.pay.console.service;

import java.util.Iterator;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;
import com.yyfax.framework.common.Log;
import com.yyfax.pay.common.annotation.BusiType;
import com.yyfax.pay.common.enums.BusiTypeEnum;
import com.yyfax.pay.common.exception.PayExceptionCode;

@Service
public class ResolverAdaptService {

	Logger logger = LoggerFactory.getLogger(getClass());

	private Map<BusiTypeEnum, CommonExceptionService> handlerMap = Maps.newHashMap();

	@Resource
	ApplicationContext context;

	@PostConstruct
	void init() {
		Map<String, CommonExceptionService> serviceMap = context.getBeansOfType(CommonExceptionService.class);
		Iterator<Map.Entry<String, CommonExceptionService>> iterator = serviceMap.entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry<String, CommonExceptionService> entry = iterator.next();
			BusiType exceptionType = AnnotationUtils.findAnnotation(entry.getValue().getClass(), BusiType.class);
			if (null != exceptionType) {
				handlerMap.put(exceptionType.value(), entry.getValue());
			}
		}

	}

	/**
	 * 获取对应的处理器
	 *
	 * @author wangjwy
	 * @date 2018/7/4 14:40
	 * @since 2.2.3
	 * @param busiTypeEnum
	 * @return com.yyfax.pay.console.service.CommonExceptionService
	 */
	public CommonExceptionService getAdaptiveService(BusiTypeEnum busiTypeEnum) {
		final String OP = "ResolverAdaptService.getAdaptiveService";
		CommonExceptionService resolverService = handlerMap.get(busiTypeEnum);
		if (null == resolverService) {
			logger.error(Log.op(OP).msg("找不到异常类型对应的处理器").kv("handlerMap", handlerMap).kv("busiTypeEnum", busiTypeEnum).toString());
			throw PayExceptionCode.SYS_ERROR.exp();
		}
		return resolverService;
	}
}
